package com.aoxon.cargo.util;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * 建立网络数据连接
 * 
 * @author ZZJ
 * 
 */
public class HttpUtil {

	// public static final String BASE_URL = "http://192.168.1.104:8083/";
	public static final String BASE_URL = "http://121.197.0.95:8080/"; // 外网
	//public static final String BASE_URL = "http://10.21.56.105:8080/cargo/";
	// //内网测试

	/**
	 * 建立HttpClient post连接
	 * 
	 * @param head
	 * @param url
	 * @param paramsList
	 * @return 服务器响应的字符串数据
	 * @throws Exception
	 */
	public static String doPost(String url, Map<String, String> paramsList)
			throws Exception {
		// 建立post连接和参数
		HttpPost httpRequest = new HttpPost(url);
		Log.e("url", url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (String key : paramsList.keySet()) {
			params.add(new BasicNameValuePair(key, paramsList.get(key)));
		}

		// 设置请求头和编码
		httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		Log.i("params", "params=  " + params.toString());

		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 6000);// 设置请求超时的时间
		HttpConnectionParams.setSoTimeout(httpParams, 6000); // 设置获取数据超时的时间
		HttpClient httpClient = new DefaultHttpClient(httpParams);

		// 获取响应
		HttpResponse httpResponse = httpClient.execute(httpRequest);

		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			String result = EntityUtils.toString(httpResponse.getEntity());
			Log.i("postResponse", "postResponse--------" + result);
			return result;
		}

		return null;
	}

	/**
	 * 建立URL实现文件上传
	 * 
	 * @param strUrl
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static String uploadFile(String strUrl, String filePath)
			throws Exception {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
		Log.i("HttpUtil", "UpLoad file name is: " + fileName);
		Log.i("HttpUtil", "UpLoad file path is: " + filePath);
		try {
			URL url = new URL(strUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			con.setConnectTimeout(10000);
			con.setReadTimeout(30000);
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"file1\";filename=\"" + fileName + "\"" + end);
			ds.writeBytes(end);

			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(filePath);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];

			int length = -1;
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

			/* close streams */
			fStream.close();
			ds.flush();

			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer result = new StringBuffer();
			while ((ch = is.read()) != -1) {
				result.append((char) ch);
			}
			ds.close();
			Log.i("uploadFile",
					"uploadFileResponse--------" + result.toString());
			return result.toString();
		} catch (Exception e) {
			Log.e("HttpUtil", "upload file fail for : " + fileName);
			e.printStackTrace();
		}
		return null;
	}

}
